package com.jqb.jsplab.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;

import com.jqb.jsplab.dao.factory.DaoFactory;
import com.jqb.jsplab.dao.proxy.StudentDaoProxy;
import com.jqb.jsplab.vo.Student;

public class UserOperateServlet extends HttpServlet {

	private static final long serialVersionUID = 2628097151835122413L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ByteArrayOutputStream bos =null;		
		String useroperate = null;
		StudentDaoProxy studentdaoproxy = null;
		useroperate = request.getParameter("useroperate");
		try {
			studentdaoproxy = DaoFactory.getInstanceStudentDaoProxy();
		} catch (Exception e) {
			e.printStackTrace();
		}
		/**
		 * 验证登录
		 * */
		if ("login".equals(useroperate)) {
			String username = null;
			String password = null;
			username = request.getParameter("username");
			password = request.getParameter("password");
			boolean islogin = false;
			try {
				islogin = studentdaoproxy.isLogin(username, password);
				if (islogin) {
					request.setAttribute("msg", "login successed...");
					request.getRequestDispatcher("/jspdemo/login.jsp").forward(request, response);
				} else {
					request.setAttribute("msg", "login failed...");
					request.getRequestDispatcher("/jspdemo/login.jsp").forward(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		/**
		 * 通过id查找用户
		 * */
		if ("findstudent".equals(useroperate)) {
			int id = Integer.parseInt(request.getParameter("id"));
			Student student = null;
			try {
				student = studentdaoproxy.findStudentById(id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("student", student);
			request.getRequestDispatcher("/jspdemo/link2oracle.jsp").forward(request, response);
		}
		/**
		 * 通过id查找用户
		 * */
		if ("findstudent1".equals(useroperate)) {
			int id = Integer.parseInt(request.getParameter("id"));
			Student student = null;
			try {
				student = studentdaoproxy.findStudentById(id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("student", student);
			request.getRequestDispatcher("/jspdemo/search.jsp").forward(request, response);
		}
		/**
		 * 用户注册
		 * */
		if ("regist".equals(useroperate)) {
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			Student student = new Student();
			student.setName(name);
			student.setPassword(password);
			boolean flag = false;
			try {
				flag = studentdaoproxy.createStudent(student);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (flag) {
				request.setAttribute("registmsg", "注册成功 ,欢迎您：" + name);
			} else {
				request.setAttribute("registmsg", "注册失败");
			}
			request.getRequestDispatcher("/jspdemo/regist.jsp").forward(
					request, response);
		}
		/**
		 * Ajax判断用户是否已存在
		 * */
		if ("isexist".equals(useroperate)) {
			boolean flag = false;
			PrintWriter out = response.getWriter();
			String name = request.getParameter("name");
			String regex = "^\\S+$";
			try {
				flag = studentdaoproxy.isStudentExist(name);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!flag && name.matches(regex)) {
				out.print("yes");
			} else {
				out.print("no");
			}
		}
		/**
		 * Ajax获取数据库用户ID
		 * */
		if ("search".equals(useroperate)) {
			try {
				int id[] = studentdaoproxy.findStudentId();
				/**
				 * <ids><id>1000</id>...</ids>
				 * DOM解析
				 * */
				/*
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder docbuilder = dbf.newDocumentBuilder();
				Document doc = docbuilder.newDocument();
				Element root = doc.createElement("ids");
				
				for(int i=0;i<id.length;i++){
					Element eid = doc.createElement("id");
					Text text = doc.createTextNode(""+id[i]);
					eid.appendChild(text);
					root.appendChild(eid);
				}
				doc.appendChild(root);
				TransformerFactory tff = TransformerFactory.newInstance();
				Transformer tf = tff.newTransformer();
				tf.setOutputProperty(OutputKeys.ENCODING,"utf-8");
				DOMSource source = new DOMSource(doc);
				bos = new ByteArrayOutputStream();
				StreamResult result = new StreamResult(bos);
				tf.transform(source, result);
				PrintWriter out = response.getWriter();
				out.print(bos);
				*/
				/**
				 * JDOM解析
				 * */
				Document doc = new Document();
				Element eids = new Element("ids");
				doc.addContent(eids);
				
				for(int i=0;i<id.length;i++){
					Element eid = new Element("id");
					eid.setText(""+id[i]);
					eids.addContent(eid);
				}
				
				XMLOutputter output = new XMLOutputter();
				PrintWriter out = response.getWriter();
				bos = new ByteArrayOutputStream();
				//设置编码
				//output.setFormat(output.getFormat().setEncoding("utf-8"));
				output.output(doc,bos);
				//也可以直接写入PrintWrite,但是最后必须使用flush刷新
//				output.output(doc,out);
				out.print(bos);
//				out.flush();
				/**
				 * DOM4J解析
				 * */
				/*
				Document doc = DocumentHelper.createDocument();
				Element eids = doc.addElement("ids");
				for(int i=0;i<id.length;i++){
					Element eid = eids.addElement("id");
					eid.setText(""+id[i]);
				}
				bos = new ByteArrayOutputStream();
				//设置编码
				//OutputFormat format = new OutputFormat();
				//format.setEncoding("utf-8");
				//XMLWriter writer1 = new XMLWriter(bos,format);
				XMLWriter writer = new XMLWriter(bos);
				writer.write(doc);
				PrintWriter out = response.getWriter();
				out.print(bos);
				*/
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
